<?php
     /**
     * 创建返回数据的格式
     * @code 状态码
     * @message 返回的消息说明
     * @data 返回的数据
     */
    function genBody($code, $message = '', $data = '')
    {
        $arr = array('code' => "$code");
        if( ! empty($message))
        {
            $arr['message'] = $message;
        }
        if( ! empty($data))
        {
            // 如果  $data 是数组，将数组中的所有的值转换为字符串类型兼容 IOS 端
            if(is_array($data))
            {
                strArrayVal($data);
            }else{
                $data = (string)$data;
            }
            $arr['data'] = $data;
        }
        return $arr;
    }

    /**
     * 将数组的所有值转换为字符串类型
     * @param $arr
     */
    function strArrayVal(&$arr){
        foreach ($arr as $k => $val) {
            if (is_array($arr[$k])) {
                strArrayVal($arr[$k]);
            } else {
                $arr[$k] = (string)$arr[$k];
            }
        }
    }


    /**
     * @param $filename 日志全路径
     * @param $data 日志内容
     * @param $mode 记录模式
     */
    function monitor_log($filename, $data, $mode)
    {
        if(is_array($data))
        {
            $data = var_export($data, true);
        }
        file_put_contents($filename, $data ."\r\n", $mode);
    }



// 图片添加
     function check(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->autoSub  = true;
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); //允许上传的文件后缀
        //$upload->savePath = '/Public/uploads/'; // 设置附件上传目录

        //上传文件
        $info = $upload->upload();
    //        var_dump($info);die;
        if( ! $info) {
            return false;
        }
        // 保存当前数据对象
        $data['pic'][0] = '/'.Uploads.'/'.$info['weixin']['savepath'].$info['weixin']['savename'];
        $data['pic'][1] = '/'.Uploads.'/'.$info['logo']['savepath'].$info['logo']['savename'];

        return $data['pic'];
    }


    function check_user_status($id){

        $id = $_SESSION['user']['userId'];

        $res_status  = M('status')->where("userId = '".$id."' and status = 1")->find();

        if($res_status){

            $now = time();

            if($res_status['endTime'] <= $now){
               
                $arr_status['status'] = 1;
                $res_save_status = M('status')->where("id = '".$res_status['id']."'")->save($arr_status); // 超过时间  该用户脱离判断状态
                
                $arr_userstatus['status'] = 3;
                $res_userstatus = M('userstatus')->where("userId = '".$res_status['pid']."'")->save($arr_userstatus);

            }
        }
    }


    function get_update($level,$uid,$pid){

        if($level == 4){

            $arr_user['level'] = 4;
            $arr_user['pid'] = 0;

            $res_user = M('user')->where('id = "'.$uid.'"')->find();
            $table1 = 'detail'.$res_user['level'];
            $table2 = 'pic'.$res_user['level'];


            $find_detail = M($table1)->where('id = "'.$res_user['detailid'].'"')->find();
    //            var_dump($find_detail);die;
            $find_pic = M($table2)->where('id = "'.$res_user['picid'].'"')->find();

            unset($find_detail['id']);
            unset($find_pic['id']);


            $find_detail['userId'] = $find_detail['userid'];
            $find_detail['useredId'] = $find_detail['useredid'];
            $find_pic['userId'] = $find_pic['userid'];

            $res_detail = M('detail4')->add($find_detail);
            $res_pic = M('pic4')->add($find_pic);

            $arr_user['detailId'] = $res_detail;
            $arr_user['picId'] = $res_pic;

            // 分配名额
            $save_user = M('user')->where('id = "'.$uid.'"')->save($arr_user);

            if($save_user){
                return 1;
            }else{
                return 0;
            }

        }else{

            $arr_user['level'] = $level;
            $arr_user['pid'] = $pid;

            $res_user = M('user')->where('id = "'.$uid.'"')->find();

            if($level == $res_user['level']){

                return true;
            }

            $table1 = 'detail'.$res_user['level'];
            $table2 = 'pic'.$res_user['level'];


            $find_detail = M($table1)->where('id = "'.$res_user['detailid'].'"')->find();
            $find_pic = M($table2)->where('id = "'.$res_user['picid'].'"')->find();

            unset($find_detail['id']);
            unset($find_pic['id']);

            $table3 = 'detail'.$level;
            $table4 = 'pic'.$level;

            $find_detail['userId'] = $find_detail['userid'];
            $find_detail['useredId'] = $find_detail['useredid'];
            $find_pic['userId'] = $find_pic['userid'];

            $res_detail = M($table3)->add($find_detail);
            $res_pic = M($table4)->add($find_pic);

            $arr_user['detailId'] = $res_detail;
            $arr_user['picId'] = $res_pic;

            $save_user = M('user')->where('id = "'.$uid.'"')->save($arr_user);

            if($save_user){
                return 1;
            }else{
                return 0;
            }

        }
    }


/**
     * 获取图片路径
     * @param $id
     * @param string $field
     * @return bool|string
     */
    function getImgPath($images_id){
        $info = M('picture')->where(['id'=>$images_id])->find();
        if($info){
            $path = __ROOT__.'/'.$info['path'];
        }else{
            $path = false;
        }
        return $path;
    }

    /**
     * 内容输出时,将内容中的base64_images转换为base64
     * @param $content  文章内容
     * @param $images_id 图片id
     * @return mixed|string
     */
    function content_images($content, $images_id){
        $pattern = '/base64_images/U';
        preg_match($pattern,$content,$res);
        if($res){
            if($images_id) {
                $ids = unserialize($images_id);
                foreach ($ids as $key => $value) {
                    $img_path = getImgPath($value);
                    $content = preg_replace($pattern, $img_path, $content, 1);
                }
            }
        }
        return $content;
    }


    /**
     * 内容转换，将base64,转换为简化的base64_images,进行内容与图片分离
     * @param $content
     * @return mixed
     */
    function content_conversion($content){
        $pattern = '/<img src="(.*)"/U';
        preg_match_all($pattern, $content, $res);
        if(!$res[1]) {
            $data['content'] = $content;
            $data['images_id'] = '';
            return $data;
        }
        foreach ($res[1] as $key => $value) {
            $images[] = base64_to_imgid($value);
        }
        foreach ($images as $key => $value) {
            $content = preg_replace('/data:.*"/U', 'base64_images"', $content, 1);
        }
        $data['content'] = $content;            //文章内容
        $data['images_id'] = serialize($images);//图片id序列化
        return $data;
    }

    /**
     * base64转换为图片存储,图片路径存储在picture数据表。
     * @param $base64
     * @return int|mixed|string 返回图片id
     */
    function base64_to_imgid($base64){
        //对base64进行正则匹配
        preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result);

        //图片格式
        $type = $result[2];

        //实现判断图片是否上传过
        $pattern = '/data:.*base64/U';
        //获取base64的数据
        $res = preg_replace($pattern, '', $base64);
        $str = base64_decode($res);
        $md5 = md5($str);
        $sha1 = sha1($str);
        $res = M('picture')->where(['md5'=>$md5,'sha1'=>$sha1])->find();
        if ($res) {
            //如果图片存在，则返回图片id
            return $res['id'];
        }else{
            //存储目录
            $PATH = 'Uploads/picture/'. date('Y-m-d', time()) . "/";

            //判断目录是否存在，不存在则创建
            if (!is_dir($PATH)) {
                mkdir($PATH, 0777, true);
            }

            //文件名
            $name = md5(rand(100, 999) . time());

            //图片路径
            $imgPath = $PATH . $name . '.' . $type;

            //拼装数据
            $data = [
                'path'        => $imgPath,
                'md5'         => $md5,
                'sha1'        => $sha1,
                'create_time' => time(),
            ];

            //插入数据到数据表
            $id = M('picture')->add($data);

            //返回图片id
            return $id;
        }
    }

    /**
     * 获取分类树(无限级分类)
     * @param $arr
     * @param int $pid 父级id
     * @param int $level 级别
     * @return array
     */
    function getTree($arr,$pid=0,$level=0){
        static $list = array();
        foreach($arr as $value){
            if($value['pid'] == $pid){
                if($level == 0){
                    $value['level'] = '';
                }else{
                    $value['level'] = $level == 1 ? str_repeat('|&nbsp;---&nbsp;',$level) : '|'.str_repeat('&nbsp;---&nbsp;',$level);
                }
                $list[] = $value;
                getTree($arr,$value['id'],$level+1);
            }
        }
        return $list;
    }

    /**
     * 获取图片的地址
     * @param $img_id @图片id
     * @return string
     */
    function getImage($img_id){
        $res = M('Picture')->where(['id'=>$img_id])->find();
        $url = __ROOT__.'/'.$res['path'];
        return $url;
    }

    /**
     * 格式化字节大小
     * @param  number $size      字节数
     * @param  string $delimiter 数字和单位分隔符
     * @return string            格式化后的带单位的大小
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    function format_bytes($size, $delimiter = '') {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
        return round($size, 2) . $delimiter ."&nbsp;".$units[$i];
    }

    function getsystem(){

        $data = M('system1')->where('id = 1')->find();
        return $data;
    }

    /*
        * 短信开关检查
        * @return false: 关闭, true: 开启
        */
    function isMsgOn(){
        $msg_cfg = C('message');
        return $msg_cfg['switch'];
    }


    /**
     * @param string $url
     * @param string $param
     * @return 成功返回相应数据，失败返回 false
     */
    function request_post($url = '', $param = '')
    {
        if( !empty($url) && !empty($param))
        {
            if( ! function_exists('curl_init'))
            {
                error_log('curl_init function not found .');
                return false;
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url); // 设置 url
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1); // post 提交方式
            if($param) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
            }
            $data = curl_exec($ch);
            return $data;
        }else{
            return false;
        }
    }


